import axios from 'axios';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { BASE_URL, REQUEST_TIMEOUT, RETRY_CONFIG } from '../config/apiConfig';

// 创建axios实例
const apiClient = axios.create({
  baseURL: BASE_URL,
  timeout: REQUEST_TIMEOUT,
  headers: {
    'Content-Type': 'application/json'
  }
});

// 请求拦截器 - 添加token
apiClient.interceptors.request.use(
  async (config) => {
    try {
      const token = await AsyncStorage.getItem('userToken');
      if (token) {
        config.headers.Authorization = `Bearer ${token}`;
      }
    } catch (error) {
      console.error('获取token失败:', error);
    }
    return config;
  },
  (error) => {
    return Promise.reject(error);
  }
);

// 响应拦截器 - 处理错误
apiClient.interceptors.response.use(
  (response) => {
    return response.data;
  },
  async (error) => {
    const originalRequest = error.config;
    
    // 处理401错误（token过期或无效）
    if (error.response?.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true;
      
      try {
        // 尝试刷新token或重新登录
        await AsyncStorage.removeItem('userToken');
        // 这里可以导航到登录页面
        // navigation.navigate('Login');
        return Promise.reject(new Error('请重新登录'));
      } catch (refreshError) {
        return Promise.reject(refreshError);
      }
    }
    
    // 处理其他错误
    const errorMessage = error.response?.data?.message || 
                       error.response?.data?.error || 
                       error.message || '请求失败，请稍后重试';
    
    return Promise.reject(new Error(errorMessage));
  }
);

// 带重试逻辑的请求函数
const requestWithRetry = async (requestFn, retries = RETRY_CONFIG.MAX_RETRIES) => {
  try {
    return await requestFn();
  } catch (error) {
    if (retries > 0) {
      console.warn(`请求失败，${RETRY_CONFIG.RETRY_DELAY}ms后重试，剩余重试次数: ${retries - 1}`);
      
      // 等待一段时间后重试
      await new Promise(resolve => setTimeout(resolve, RETRY_CONFIG.RETRY_DELAY));
      
      return requestWithRetry(requestFn, retries - 1);
    }
    
    // 重试次数用完，抛出错误
    throw error;
  }
};

// 封装常见的HTTP请求方法
export const api = {
  get: (url, params = {}) => {
    return requestWithRetry(() => apiClient.get(url, { params }));
  },
  
  post: (url, data = {}) => {
    return requestWithRetry(() => apiClient.post(url, data));
  },
  
  put: (url, data = {}) => {
    return requestWithRetry(() => apiClient.put(url, data));
  },
  
  delete: (url, params = {}) => {
    return requestWithRetry(() => apiClient.delete(url, { params }));
  },
  
  // 不带重试的请求
  getWithoutRetry: (url, params = {}) => {
    return apiClient.get(url, { params });
  },
  
  postWithoutRetry: (url, data = {}) => {
    return apiClient.post(url, data);
  },
  
  // 上传文件
  upload: (url, formData) => {
    return requestWithRetry(() => 
      apiClient.post(url, formData, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
    );
  }
};

// 导出原始的axios实例，用于特殊需求
export { apiClient };